package com.example.user

import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.network.*
import java.io.IOException

class RegisterActivity : AppCompatActivity(), View.OnClickListener {
    //注册控件
    private lateinit var backButton: ImageView
    private lateinit var nextButton: Button
    private lateinit var btnGetVerificationCode: Button
    private lateinit var usernameEditText: EditText
    private lateinit var verificationCodeEditText: EditText
    private lateinit var checkBoxAgreement: CheckBox
    private var countDownTimer: CountDownTimer? = null

    //用户名
    private var userName: String? = null
    // 验证码
    private var verCode: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.register_activity)

        //将backButton绑定为title_bar_back，并设置相应的监听器
        backButton = findViewById(R.id.title_bar_back)
        backButton.setOnClickListener(this)

        //将nextButton进行绑定，并设置相应的监听器
        nextButton = findViewById(R.id.btn_next_step)
        nextButton.isEnabled = false // 默认禁用下一步按钮
        nextButton.setOnClickListener(this)

        // 初始化用户协议复选框
        checkBoxAgreement = findViewById(R.id.check_box_agreement)
        checkBoxAgreement.setOnCheckedChangeListener { _, isChecked ->
            // 根据复选框状态启用/禁用下一步按钮
            nextButton.isEnabled = isChecked
        }
        
        //绑定用户名输入框
        usernameEditText = findViewById(R.id.Username)
        
        //绑定验证码输入框
        verificationCodeEditText = findViewById(R.id.PassWord)

        //绑定获取验证码按钮框，并设置相对应地监听器
        btnGetVerificationCode = findViewById(R.id.btn_get_verification_code)
        btnGetVerificationCode.setOnClickListener(this)
        // 初始化验证码倒计时计时器
    }

    // 发送验证码
    private fun SendVerCode() {
        //对输入进行筛选
        userName = usernameEditText.text.toString()
        if (!userName.isNullOrEmpty() && userName!!.matches("^1\\d{10}$".toRegex())) {
            //开始发送获取验证码的网络请求，并提示发送成功
            Toast.makeText(this, R.string.user_account_verification_code_sent, Toast.LENGTH_LONG).show()
            Log.d("TAG", "号码正确已发送验证码")
            //发送验证码网络请求
            SendRequest.sendVerCode(userName!!)
            //初始化计时器
            CountTimerInit()
        } else {
            Log.d("TAG", "请输入正确的号码")
            Toast.makeText(this, R.string.user_account_input_username_tip, Toast.LENGTH_LONG).show()
        }
    }

    // 检查验证码
    private fun checkVerCode() {
        verCode = verificationCodeEditText.text.toString()
        try {
            SendRequest.checkVerCode(userName!!, verCode!!, object : CheckResultListener {
                override fun onSuccess(desc: String) {
                    if (desc == "成功代理") {
                        Toast.makeText(this@RegisterActivity, desc, Toast.LENGTH_SHORT).show()
                        val intent = Intent(this@RegisterActivity, RegisterPassword::class.java)
                        intent.putExtra("userName", userName)
                        intent.putExtra("verCode", verCode)
                        startActivity(intent)
                    } else {
                        Toast.makeText(this@RegisterActivity, "代理失败", Toast.LENGTH_SHORT).show()
                    }
                }

                override fun onFail(msg: String) {
                    Toast.makeText(this@RegisterActivity, msg, Toast.LENGTH_SHORT).show()
                }
            })
        } catch (e: Exception) {
            throw IOException(e)
        }
    }

    // 倒计时初始化
    private fun CountTimerInit() {
        countDownTimer?.cancel()

        countDownTimer = object : CountDownTimer(60000, 1000) {
            override fun onFinish() {
                btnGetVerificationCode.text = getString(R.string.user_account_get_verification_code)
                btnGetVerificationCode.isEnabled = true
            }

            //这里每过1秒就运行这个回调函数
            override fun onTick(millisUntilFinished: Long) {
                Log.d("TAG", String.format("当前是%d秒", millisUntilFinished / 1000))
                btnGetVerificationCode.text = getString(R.string.user_account_verification_code_countdown, millisUntilFinished / 1000)
                btnGetVerificationCode.isEnabled = false
            }
        }.start()
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.btn_next_step -> {
                Log.i("TAG", "注册页面即将进入设置密码页面")
                try {
                    checkVerCode()
                } catch (e: IOException) {
                    throw RuntimeException(e)
                }
            }
            R.id.title_bar_back -> {
                finish()
            }
            R.id.btn_get_verification_code -> {
                Log.d("TAG", "点击了获取验证码按钮")
                SendVerCode()
            }
        }
    }

    /* ③ 若页面被销毁，则注销掉当前定时器 */
    override fun onDestroy() {
        super.onDestroy()
        countDownTimer?.cancel()
        countDownTimer = null
    }
}